package Classic150;

import LinkedList.ListNode;

public class 删除链表的倒数第N个结点 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        /*
            快慢双指针
         */
        ListNode fast = head;
        ListNode slow = head;
        for (int i = 0; i < n; i++) fast = fast.next;
        if (fast == null) return head.next;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;

        /*
            回溯时从后往前找到结点进行操作
         */
        /*int index = getIndex(head, n);
        if (index == n) return head.next;
        return head;*/
    }

    private int getIndex(ListNode root, int n) {
        if (root == null) return 0;
        int index = getIndex(root.next, n) + 1;
        if (index == n + 1) root.next = root.next.next;
        return index;
    }
}
